<!--
  speedy-vision.js
  GPU-accelerated Computer Vision for JavaScript
  Copyright 2020-2024 Alexandre Martins <alemartf(at)gmail.com>

  Licensed under the Apache License, Version 2.0 (the "License");
  you may not use this file except in compliance with the License.
  You may obtain a copy of the License at
  
      http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.

  optical-flow.html
  Feature tracking demo
-->
<!doctype html>
<html>
    <head>
        <meta charset="utf-8">
        <meta name="description" content="speedy-vision.js: GPU-accelerated Computer Vision for JavaScript">
        <meta name="author" content="Alexandre Martins">
        <title>Optical flow - feature tracking</title>
        <link href="demo-base.css" rel="stylesheet">
        <script src="demo-base.js"></script>
        <script src="../dist/speedy-vision.js"></script>
    </head>
    <body>
        <h1>LK optical flow</h1>
        <p><em>Click on a <strong>moving region</strong> of the video to track it!</em></p>
        <form autocomplete="off">
            <div>
                <label for="window-size">Window size</label>
                <select id="window-size">
                    <option value="5">5x5</option>
                    <option value="7">7x7</option>
                    <option value="9">9x9</option>
                    <option value="11" selected>11x11</option>
                    <option value="13">13x13</option>
                    <option value="15">15x15</option>
                    <option value="21">21x21</option>
                </select>
                <label for="levels">Pyramid levels</label>
                <select id="levels">
                    <option value="1">1</option>
                    <option value="2">2</option>
                    <option value="3" selected>3</option>
                    <option value="4">4</option>
                    <option value="5">5</option>
                    <option value="6">6</option>
                    <option value="7">7</option>
                </select>
                <label for="discard-threshold">Discard threshold</label>
                <select id="discard-threshold">
                    <option value="0.0">0.0</option>
                    <option value="0.0001" selected>0.0001</option>
                    <option value="0.001">0.001</option>
                    <option value="0.01">0.01</option>
                </select>
            </div>
            <div class="separator"></div>
            <div>
                <label for="number-of-iterations">Max. iterations</label>
                <select id="number-of-iterations">
                    <option value="3">3</option>
                    <option value="5">5</option>
                    <option value="8">8</option>
                    <option value="15">15</option>
                    <option value="20">20</option>
                    <option value="30" selected>30</option>
                </select>
                <label for="epsilon">Epsilon for early termination</label>
                <select id="epsilon">
                    <option value="0">0</option>
                    <option value="0.01" selected>0.01</option>
                    <option value="0.03">0.03</option>
                </select>
                <span>
                    &nbsp;&nbsp;
                    <a href="javascript:reset()">Reset values</a>
                </span>
            </div>
            <div class="separator"></div>
            <div>
                <label for="speed-slider">Video speed</label>
                <input type="range" id="speed-slider" min="0.10" max="2" value="1" step="0.01">
            </div>
        </form>
        <div>
            <span id="status"></span>
            <canvas id="canvas-demo" style="cursor:pointer"></canvas>
        </div>
        <div>
            <button id="play">Play / pause</button>
            &nbsp;
            <button id="detect">Detect features</button>
            &nbsp;
            <button id="clear">Clear features</button>
        </div>
        <video id="video"
            poster="../assets/loading.jpg"
            width="640" height="360"
            preload="auto"
            muted hidden playsinline
            title="Free to use video by Free Videos, https://www.pexels.com/pt-br/foto/853889/">
                <source src="../assets/people.webm" type="video/webm" />
                <source src="../assets/people.mp4" type="video/mp4" />
        </video>
        <script>
let userPoints = [];

window.onload = async function()
{
    // get DOM elements
    const windowSize = document.getElementById('window-size');
    const discardThreshold = document.getElementById('discard-threshold');
    const levels = document.getElementById('levels');
    const numberOfIterations = document.getElementById('number-of-iterations');
    const epsilon = document.getElementById('epsilon');

    // load the video
    const video = document.getElementById('video');
    const media = await Speedy.load(video);
    video.play();

    // create the pipeline
    const pipeline = Speedy.Pipeline();
    const imgsrc = Speedy.Image.Source();
    const kpsrc = Speedy.Keypoint.Source();

    const grey = Speedy.Filter.Greyscale();
    const pyr = Speedy.Image.Pyramid();
    const harris = Speedy.Keypoint.Detector.Harris();
    const clipper = Speedy.Keypoint.Clipper();

    const buf = Speedy.Image.Buffer();
    const bufpyr = Speedy.Image.Pyramid();

    const lk = Speedy.Keypoint.Tracker.LK();
    const mixer = Speedy.Keypoint.Mixer();
    const sink = Speedy.Keypoint.SinkOfTrackedKeypoints();

    imgsrc.media = media;
    harris.quality = 0.10;
    harris.capacity = 0;

    imgsrc.output().connectTo(grey.input());
    grey.output().connectTo(pyr.input());
    grey.output().connectTo(buf.input());
    buf.output().connectTo(bufpyr.input());

    bufpyr.output().connectTo(harris.input());
    harris.output().connectTo(clipper.input());
    clipper.output().connectTo(mixer.input('in1'));
    kpsrc.output().connectTo(mixer.input('in0'));

    bufpyr.output().connectTo(lk.input('previousImage'));
    pyr.output().connectTo(lk.input('nextImage'));
    mixer.output().connectTo(lk.input('previousKeypoints'));

    lk.output().connectTo(sink.input());
    lk.output('flow').connectTo(sink.input('flow'));

    pipeline.init(imgsrc, grey, pyr, harris, kpsrc, clipper, buf, bufpyr, lk, mixer, sink);

    // Main loop
    let detect = false, clear = false;
    (function() {
        const canvas = addMouseListener(setupCanvas('canvas-demo', media.width, media.height, video.title));
        let keypoints = [], frameReady = false;

        async function update()
        {
            // prevent rendering before running the pipeline
            frameReady = false;

            // find new keypoints
            harris.capacity = 0;
            if(detect) {
                if(keypoints.length < 400)
                    harris.capacity = 2048;
                detect = false;
            }

            // handle new points added by the user
            if(userPoints.length > 0) {
                keypoints.push(...userPoints);
                userPoints.length = 0;
            }

            // clear all keypoints
            if(clear) {
                keypoints.length = userPoints.length = 0;
                clear = false;
            }

            // update parameters
            kpsrc.keypoints = keypoints;
            lk.windowSize = Speedy.Size(Number(windowSize.value), Number(windowSize.value));
            lk.levels = Number(levels.value);
            lk.discardThreshold = Number(discardThreshold.value);
            lk.numberOfIterations = Number(numberOfIterations.value);
            lk.epsilon = Number(epsilon.value);
            clipper.size = 200;

            // run the pipeline
            const result = await pipeline.run();
            keypoints = result.keypoints;

            // repeat
            frameReady = true;
            setTimeout(update, 1000 / 60);
        }
        update();

        function render()
        {
            if(frameReady) {
                renderMedia(media, canvas);
                renderFlowVectors(canvas, keypoints, '#f22', 3);
                renderKeypoints(canvas, keypoints, '#f22');
            }

            frameReady = false;
            requestAnimationFrame(render);
        }
        render();

        setInterval(() => renderStatus(keypoints), 200);
    })();

    // play/pause
    const playButton = document.getElementById('play');
    playButton.onclick = () => video.paused ? video.play() : video.pause();

    // video speed
    const speedSlider = document.getElementById('speed-slider');
    speedSlider.oninput = () => video.playbackRate = speedSlider.value;

    // detect features
    const detectButton = document.getElementById('detect');
    detectButton.onclick = () => detect = true;

    // clear features
    const clearButton = document.getElementById('clear');
    clearButton.onclick = () => clear = true;

    // restart the video and clear the features
    video.onended = () => {
        clear = true;
        video.currentTime = 0.2;
        video.play();
    };
}

function renderFlowVectors(canvas, features, color = 'red', length = 1)
{
    const context = canvas.getContext('2d');

    context.beginPath();
    for(let i = 0; i < features.length; i++) {
        const feature = features[i];
        const flow = feature.flow;

        // draw flow vector
        context.moveTo(feature.x - flow.x * length, feature.y - flow.y * length);
        context.lineTo(feature.x, feature.y);
    }
    context.strokeStyle = color;
    context.lineWidth = 2;
    context.stroke();
}

function addMouseListener(canvas)
{
    canvas.addEventListener('mousedown', ev => {
        const position = cursorPosition(canvas, ev);
        userPoints.push({ position });
    });

    return canvas;
}

function cursorPosition(canvas, event)
{
    const rect = canvas.getBoundingClientRect();
    const x = event.clientX - rect.left;
    const y = event.clientY - rect.top;

    return { x, y };
}

function reset()
{
    const options = document.querySelectorAll('select option');
    for(const option of options)
        option.selected = option.defaultSelected;

    const slider = document.getElementById('speed-slider');
    slider.value = slider.defaultValue;
    slider.dispatchEvent(new Event('input'));
}
        </script>
        <section id="speedy-vision">
            <span>Powered by <a href="https://github.com/alemart/speedy-vision" target="_blank">speedy-vision.js</a></span>
            <a href="https://github.com/sponsors/alemart" target="_blank" class="button">
                <img alt="GitHub Sponsors" src="https://img.shields.io/github/sponsors/alemart?style=for-the-badge&logo=github&label=Sponsor&labelColor=royalblue&color=gold">
            </a>
        </section>
    </body>
</html>